//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package zmee.pmas.opplugin;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.pmgt.pmas.business.helper.ProjectBudgetBuilder;
import kd.pmgt.pmbs.common.utils.BudgetControlHelper;
import zmee.util.BosUtil;

public class ProjectBudgetGenerateHelper {
    public ProjectBudgetGenerateHelper() {
    }

    public static void generateProjectBudget(DynamicObject budgetObj, List<DynamicObject> updateProjectItems, List<DynamicObject> addProjectItems, String sourceType) {
        DynamicObjectCollection treeEntryEntity = budgetObj.getDynamicObjectCollection("treeentryentity");
        if (treeEntryEntity != null && !treeEntryEntity.isEmpty()) {
            Iterator var5 = treeEntryEntity.iterator();

            while(var5.hasNext()) {
                DynamicObject budgetEntryObj = (DynamicObject)var5.next();
                DynamicObject projectBudgetItem = budgetEntryObj.getDynamicObject("projectbudgetitem");
                if (projectBudgetItem == null) {
                    projectBudgetItem = (new ProjectBudgetBuilder(budgetEntryObj.getLong("id"))).sourceType(sourceType).project(budgetObj.getDynamicObject("project")).parent(getProjectBudgetParentId(budgetEntryObj, treeEntryEntity)).currency(budgetObj.getDynamicObject("currency")).build();
                    setProjectBudgetByBudgetEntry(projectBudgetItem, budgetEntryObj, budgetObj.getDate("year"));
                    addProjectItems.add(projectBudgetItem);
                    budgetEntryObj.set("projectbudgetitem", budgetEntryObj.getPkValue());
                } else {
                    projectBudgetItem = BusinessDataServiceHelper.loadSingle(projectBudgetItem.getPkValue(), "pmas_projectbudget");
                    projectBudgetItem.set("parent", getProjectBudgetParentId(budgetEntryObj, treeEntryEntity));
                    setProjectBudgetByBudgetEntry(projectBudgetItem, budgetEntryObj, budgetObj.getDate("year"));
                    updateProjectItems.add(projectBudgetItem);
                }
            }
        }

        DynamicObject project = budgetObj.getDynamicObject("project");
        if (project != null) {
            Map<String, Map<String, DynamicObject>> controlRateMap = BudgetControlHelper.getControlRateMap(project.getLong("id"));
            updateProjectBudgetControlInfo(controlRateMap, updateProjectItems);
            updateProjectBudgetControlInfo(controlRateMap, addProjectItems);
        }

    }

    public static void updateProjectBudgetControlInfo(Map<String, Map<String, DynamicObject>> controlRateMap, List<DynamicObject> projectBudgetItems) {
        if (projectBudgetItems != null && !projectBudgetItems.isEmpty()) {
            Map<String, DynamicObject> projectBudgetMap = (Map)controlRateMap.get("proBudgetItemMap");
            Map<String, DynamicObject> standardBudgetMap = (Map)controlRateMap.get("budgetItemMap");

            DynamicObject projectBudget;
            for(Iterator var4 = projectBudgetItems.iterator(); var4.hasNext(); countRemainAmountInfo(projectBudget)) {
                projectBudget = (DynamicObject)var4.next();
                Long standardBudgetId = projectBudget.getLong("budgetitem");
                DynamicObject controlEntry = projectBudgetMap == null ? null : (DynamicObject)projectBudgetMap.get(projectBudget.getString("id"));
                if (controlEntry == null && standardBudgetId != 0L && standardBudgetMap != null && standardBudgetMap.get(standardBudgetId.toString()) != null) {
                    controlEntry = (DynamicObject)standardBudgetMap.get(standardBudgetId.toString());
                }

                if (controlEntry != null) {
                    BudgetControlHelper.updateProBudgetItemByParam(projectBudget, controlEntry);
                } else {
                    BudgetControlHelper.cancelProBudgetItemControl(projectBudget);
                }
            }

        }
    }

    protected static void countRemainAmountInfo(DynamicObject projectBudget) {
        BigDecimal occupyAmount = projectBudget.getBigDecimal("occupyamt") == null ? BigDecimal.ZERO : projectBudget.getBigDecimal("occupyamt");
        BigDecimal performAmount = projectBudget.getBigDecimal("performamt") == null ? BigDecimal.ZERO : projectBudget.getBigDecimal("performamt");
        BigDecimal budgetAmount = projectBudget.getBigDecimal("budgetamount") == null ? BigDecimal.ZERO : projectBudget.getBigDecimal("budgetamount");
        BigDecimal remainAmount = budgetAmount.subtract(occupyAmount).subtract(performAmount);
        projectBudget.set("remainamt", remainAmount);
        BigDecimal remainRate = BigDecimal.ZERO;
        if (budgetAmount.compareTo(BigDecimal.ZERO) != 0) {
            remainRate = remainAmount.divide(budgetAmount, 10, RoundingMode.HALF_UP);
        }

        projectBudget.set("remainrate", remainRate);
    }

    private static void setProjectBudgetByBudgetEntry(DynamicObject budgetItem, DynamicObject entry, Date curBiiDate) {
        budgetItem.set("number", BosUtil.getNumber(budgetItem));
        budgetItem.set("sequence", entry.getInt("seq"));
        budgetItem.set("budgetitem", entry.get("budgetitem") == null ? 0 : entry.getDynamicObject("budgetitem").getPkValue());
        budgetItem.set("description", entry.get("descriptionentry"));
        budgetItem.set("name", entry.get("budgetitemname"));
        budgetItem.set("siamount", entry.get("siamount"));
        budgetItem.set("viamount", entry.get("viamount"));
        budgetItem.set("vichangeamount", entry.get("vichangeamount"));
        BigDecimal proBudgetSumAmt = BigDecimal.ZERO;
        DynamicObjectCollection yearBudgetRecord = budgetItem.getDynamicObjectCollection("yearbudgetrecord");
        if (QueryServiceHelper.exists("pmas_projectbudget", budgetItem.getPkValue())) {
            DynamicObject item = null;
            Iterator var6 = yearBudgetRecord.iterator();

            while(var6.hasNext()) {
                DynamicObject record = (DynamicObject)var6.next();
                Date lastBudgetDate = record.getDate("year");
                int lastBudgetYear = lastBudgetDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate().getYear();
                int curBillYear = curBiiDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate().getYear();
                if (lastBudgetYear == curBillYear) {
                    item = record;
                    break;
                }
            }

            if (item == null) {
                createProBudgetYearRecord(budgetItem, curBiiDate, entry);
            } else {
                item.set("curyearamt", entry.get("budgetamount"));
                item.set("sumbudgetamt", item.getBigDecimal("lastyearsurplusamt").add(item.getBigDecimal("curyearamt")));
            }
        } else {
            createProBudgetYearRecord(budgetItem, curBiiDate, entry);
        }

        DynamicObject yearRecord;
        if (yearBudgetRecord.size() > 0) {
            for(Iterator var11 = yearBudgetRecord.iterator(); var11.hasNext(); proBudgetSumAmt = proBudgetSumAmt.add(yearRecord.getBigDecimal("curyearamt"))) {
                yearRecord = (DynamicObject)var11.next();
            }
        }

        budgetItem.set("budgetamount", proBudgetSumAmt);
    }

    private static void createProBudgetYearRecord(DynamicObject budgetItem, Date curBiiDate, DynamicObject entry) {
        DynamicObjectCollection yearBudgetRecord = budgetItem.getDynamicObjectCollection("yearbudgetrecord");
        DynamicObject item = yearBudgetRecord.addNew();
        if (!QueryServiceHelper.exists("pmas_projectbudget", budgetItem.getPkValue())) {
            item.set("lastyearsurplusamt", BigDecimal.ZERO);
        } else {
            item.set("lastyearsurplusamt", budgetItem.getBigDecimal("budgetamount").subtract(budgetItem.getBigDecimal("occupyamt")));
        }

        item.set("year", curBiiDate);
        item.set("curyearamt", entry.get("budgetamount"));
        item.set("sumbudgetamt", item.getBigDecimal("lastyearsurplusamt").add(item.getBigDecimal("curyearamt")));
    }

    private static Long getProjectBudgetParentId(DynamicObject entry, DynamicObjectCollection entrys) {
        long parentId = entry.getLong("pid");
        if (parentId != 0L) {
            Iterator var4 = entrys.iterator();

            while(var4.hasNext()) {
                DynamicObject budgetEntryObj = (DynamicObject)var4.next();
                long entryId = budgetEntryObj.getLong("id");
                if (parentId == entryId) {
                    long id = budgetEntryObj.getLong("projectbudgetitem_id");
                    return id == 0L ? entryId : id;
                }
            }
        }

        return 0L;
    }

    public static void generateProjectBudget(DynamicObject budget, String sourceType) {
        ArrayList<DynamicObject> updateProjectItems = new ArrayList();
        ArrayList<DynamicObject> addProjectItems = new ArrayList();
        generateProjectBudget(budget, updateProjectItems, addProjectItems, sourceType);
        if (!updateProjectItems.isEmpty()) {
            SaveServiceHelper.save(((DynamicObject)updateProjectItems.get(0)).getDataEntityType(), updateProjectItems.toArray(new DynamicObject[updateProjectItems.size()]));
        }

        if (!addProjectItems.isEmpty()) {
            SaveServiceHelper.save(((DynamicObject)addProjectItems.get(0)).getDataEntityType(), addProjectItems.toArray(new DynamicObject[addProjectItems.size()]));
        }

        DynamicObject project = budget.getDynamicObject("project");
        if (project != null) {
            Map<String, Map<String, DynamicObject>> controlRateMap = BudgetControlHelper.getControlRateMap(project.getLong("id"));
            updateProjectBudgetControlInfo(controlRateMap, updateProjectItems);
            updateProjectBudgetControlInfo(controlRateMap, addProjectItems);
        }

    }
}
